package com.ruoyi.customer.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.customer.api.domain.CustomerManagement;
import com.ruoyi.customer.api.domain.ZkxcUser;
import com.ruoyi.customer.api.domain.ZkxcUserDTO;
import com.ruoyi.customer.domain.ZkxcUserVO;
import com.ruoyi.customer.mapper.CustomerManagementMapper;
import com.ruoyi.customer.mapper.ZkxcUserMapper;
import com.ruoyi.customer.service.IZkxcUserService;
import com.ruoyi.customer.service.PushRegistrationService;
import com.ruoyi.iot.api.RemoteIotService;
import com.ruoyi.iot.api.domain.PushInfo;
import com.ruoyi.utils.IDCardGenerator;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 推送给设备的用户信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-05
 */
@Service
public class ZkxcUserServiceImpl implements IZkxcUserService {
    @Autowired
    private ZkxcUserMapper zkxcUserMapper;
    @Autowired
    private CustomerManagementMapper customerMapper;

    @Autowired
    private PushRegistrationService pushRegistrationService;

    /**
     * 查询推送给设备的用户信息
     *
     * @param id 推送给设备的用户信息主键
     * @return 推送给设备的用户信息
     */
    @Override
    public ZkxcUser selectZkxcUserById(Long id) {
        return zkxcUserMapper.selectZkxcUserById(id);
    }

    /**
     * 查询推送给设备的用户信息列表
     *
     * @param dto 推送给设备的用户信息
     * @return 推送给设备的用户信息
     */
    @Override
    public List<ZkxcUser> selectZkxcUserList(ZkxcUserDTO dto) {
        ZkxcUser zkxcUser = new ZkxcUser();
        zkxcUser.setName(dto.getName());
        zkxcUser.setIdCard(dto.getIdCard());
        zkxcUser.setStatus(dto.getStatus());
        return zkxcUserMapper.selectZkxcUserList(zkxcUser);
    }

    /**
     * 新增推送给设备的用户信息
     *
     * @param customerId 用户id
     * @return 结果
     */
    @Override
    public AjaxResult insertZkxcUser(Long customerId) {
        // 检查是否有正在进行的体检
        ZkxcUser parama = new ZkxcUser();
        parama.setCustomerId(customerId);
        parama.setStatus(0);
        if(!zkxcUserMapper.selectZkxcUserList(parama).isEmpty()){
            return AjaxResult.warn("您已存在进行中的检查,请移步到检查设备进行检查！");
        };

        // 根据 用户id查询用户信息
        CustomerManagement customer = customerMapper.selectCustomerManagementById(customerId);
        // 组装信息
        ZkxcUser zkxcUser = new ZkxcUser();
        zkxcUser.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        zkxcUser.setCustomerId(customerId);
        zkxcUser.setName(customer.getRealName());
        zkxcUser.setSexStr(customer.getSex());
        zkxcUser.setAgeData(customer.getBirthDate());
        zkxcUser.setPhone(customer.getPhoneNumber());
        zkxcUser.setIdCard(customer.getIdNumber());
        zkxcUser.setStatus(0);
        int i = zkxcUserMapper.insertZkxcUser(zkxcUser);
        return  i > 0 ? AjaxResult.success("添加成功,请移步到机器进行操作！") : AjaxResult.error();

    }

    /**
     * 修改推送给设备的用户信息
     *
     * @param zkxcUser 推送给设备的用户信息
     * @return 结果
     */
    @Override
    public int updateZkxcUser(ZkxcUser zkxcUser) {
        return zkxcUserMapper.updateZkxcUser(zkxcUser);
    }

    /**
     * 批量删除推送给设备的用户信息
     *
     * @param ids 需要删除的推送给设备的用户信息主键
     * @return 结果
     */
    @Override
    public int deleteZkxcUserByIds(Long[] ids) {
        return zkxcUserMapper.deleteZkxcUserByIds(ids);
    }

    /**
     * 删除推送给设备的用户信息信息
     *
     * @param id 推送给设备的用户信息主键
     * @return 结果
     */
    @Override
    public int deleteZkxcUserById(Long id) {
        return zkxcUserMapper.deleteZkxcUserById(id);
    }

    @Override
    public AjaxResult createZkxcUser(ZkxcUserVO vo) {
        boolean flag;

        // 1、根据手机号查询用户是否存在
        CustomerManagement customer = customerMapper.selectCustomerManagementByPhoneNumber(vo.getPhone());

        if (ObjectUtils.isNotEmpty(customer)) {

            // 2、检查用户是否 已经提交过体检
            ZkxcUser parama = new ZkxcUser();
            parama.setCustomerId(customer.getId());
            parama.setStatus(0);
            if (!zkxcUserMapper.selectZkxcUserList(parama).isEmpty()) {
                return AjaxResult.warn("您已存在进行中的检查,请移步到检查设备进行检查！");
            }

            // 客户存在，修改相关数据
            customer.setRealName(vo.getName());
            customer.setSex(vo.getSex());
            customer.setBirthDate(vo.getBirthDate());
            customer.setHeight(vo.getHeight());
            customer.setWeight(vo.getWeight());
            int i = customerMapper.updateCustomerManagement(customer);
            flag = i > 0;
        } else {
            // 创建客户
            customer = new CustomerManagement();
            customer.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
            customer.setAccount(vo.getPhone());
            customer.setNickName(vo.getName());
            customer.setRealName(vo.getName());
            customer.setSex(vo.getSex());
            customer.setHeight(vo.getHeight());
            customer.setWeight(vo.getWeight());
            customer.setBirthDate(vo.getBirthDate());
            customer.setPhoneNumber(vo.getPhone());
            // 由于身份证为必填内容，但是为了用户隐私安全，此处随机生成18位随机身份证号码（仅用于占位，不保证校验位正确）
            customer.setIdType("1");
            customer.setIdNumber(IDCardGenerator.generateIDCard(vo.getBirthDate()));
            int i = customerMapper.insertCustomerManagement(customer);
            flag = i > 0;
        }
        if (!flag) {
            return AjaxResult.error("提交失败！请联系管理员。");
        }

        // 3、创建体检用户
        ZkxcUser zkxcUser = new ZkxcUser();
        zkxcUser.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        zkxcUser.setCustomerId(customer.getId());
        zkxcUser.setName(vo.getName());
        zkxcUser.setSexStr(vo.getSex());
        zkxcUser.setAgeData(vo.getBirthDate());
        zkxcUser.setPhone(vo.getPhone());
        zkxcUser.setIdCard(customer.getIdNumber());
        zkxcUser.setStatus(0);
        int i = zkxcUserMapper.insertZkxcUser(zkxcUser);
        pushRegistrationService.pushRegistration(zkxcUser);
        return i > 0 ? AjaxResult.success("您的信息已成功提交,请移步到检查设备进行检查！") : AjaxResult.error("提交失败！请联系管理员。");
    }
}
